package com.eos.freeect.common.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.eos.freeect.common.PaginationSupport;


public class CommDaoImpl extends HibernateDaoSupport {

	/**
	 * 保存实体对象
	 * @param entity
	 * @return
	 */
	public void save(final Object entity) {
		getHibernateTemplate().save(entity);
	}
	
	/**
	 * 删除实体对象
	 * @param entity
	 * @return 
	 * @return
	 */
	public void delete(final Object entity) {
		getHibernateTemplate().delete(entity);
	}
	
	/**
	 * 根据id获得实体对象
	 * @param entity
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Object get(final Class entity, final Serializable id) {
		return getHibernateTemplate().get(entity, id);
	}

	/**
	 * 根据id获得实体对象
	 * @param entity
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Object load(final Class entity, final Serializable id) {
		return getHibernateTemplate().load(entity, id);
	}

	/**
	 * 更新实体
	 * @param entity
	 */
	public void update(final Object entity) {
		getHibernateTemplate().update(entity);

	}

	/**
	 * 通过HQL进行查询
	 * @param Hql
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List findByHql(String Hql) {
		return getHibernateTemplate().find(Hql);
	}

	/**
	 * 通过Criteria进行查询
	 * @param detachedCriteria
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List findByCriteria(DetachedCriteria detachedCriteria) {
		System.out.println(detachedCriteria.toString());
		return getHibernateTemplate().findByCriteria(detachedCriteria);

	}
	
	/**
	 * 获得满足条件的记录的条数
	 * @param detachedCriteria
	 * @return
	 */
	public int getCountByCondition(DetachedCriteria detachedCriteria) {
		Criteria criteria = detachedCriteria
				.getExecutableCriteria(getSession());
		int count = ((Integer) criteria.setProjection(Projections.rowCount())
				.uniqueResult()).intValue();
		return count;
	}

	/**
	 * 通过原始sql进行查询
	 * @param sqlStr
	 * @return
	 */
	public Object findBySql(String sqlStr) {
		final String sql=sqlStr;
		Object obj= getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				return session.createQuery(sql);
			}
		});
		return obj;
	}
	
	/**
	 * 得到session
	 * @return
	 */
	public Session TakeSession()
	{
		return getSession();
	}
	
	/**
	 * 分页查询
	 * @param detachedCriteria 分页条件
	 * @param pageSize 每页条数
	 * @param startIndex 开始编号
	 * @return
	 */
	public PaginationSupport findPageByCriteria(
			DetachedCriteria detachedCriteria, int pageSize,
			int startIndex) {
		Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
		int totalCount  = ((Integer)criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
		criteria.setProjection(null);
		
		criteria.setResultTransformer(Criteria.ROOT_ENTITY); // add by zjr;使返回的集合不是obj[],而是实体的集合
		@SuppressWarnings("unchecked")
		List items = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
		PaginationSupport ps = new PaginationSupport(items,
				totalCount, pageSize, startIndex);
		return ps;
	}
	
	/**
	 * 分页查询
	 * @param detachedCriteria 分页条件
	 * @param pageSize 每页条数
	 * @param startIndex 开始编号
	 * @param sortName 排序的属性名
	 * @param isAsc 是否升序
	 * @return
	 */
	public PaginationSupport findPageByCriteria(
			DetachedCriteria detachedCriteria, int pageSize,
			int startIndex, String sortName, boolean isAsc) {
		Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
		int totalCount  = ((Integer)criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
		criteria.setProjection(null);
		
		criteria.setResultTransformer(Criteria.ROOT_ENTITY); // add by zjr;使返回的集合不是obj[],而是实体的集合
		@SuppressWarnings("unchecked")
		List items = new ArrayList();
		if(isAsc){
			items = criteria.addOrder(Order.desc(sortName)).setFirstResult(startIndex).setMaxResults(pageSize).list();
		}
		else {
			items = criteria.addOrder(Order.desc(sortName)).setFirstResult(startIndex).setMaxResults(pageSize).list();
		}
		PaginationSupport ps = new PaginationSupport(items,
				totalCount, pageSize, startIndex);
		return ps;
	}
	
	/**
	 * 分页查询
	 * @param detachedCriteria 分页条件
	 * @param request HttpServletRequest对象用于获取每页条数和开始编号，必须要和"/WEB-INF/jsp/comm/pagingToolBar.jsp"一起使用
	 * <br/>使用"<jsp:include flush="true" page="/WEB-INF/jsp/comm/pagingToolBar.jsp" />"语句将分页工具条页面包含在你的页面中。
	 * @return 分页对象
	 */
	public PaginationSupport findPageByCriteria(DetachedCriteria detachedCriteria,HttpServletRequest request) {
		int pageSize = 5;
		if(request.getParameter("pageSize") != null) {
			pageSize = Integer.valueOf(request.getParameter("pageSize")).intValue();
		}
		int startIndex = 0;
		if(request.getParameter("startIndex") != null) {
			startIndex = Integer.valueOf(request.getParameter("startIndex")).intValue();
		}
		return findPageByCriteria(detachedCriteria, pageSize, startIndex);
	}
	
	/**
	 * 分页查询
	 * @param detachedCriteria 分页条件
	 * @param request HttpServletRequest对象用于获取每页条数和开始编号，必须要和"/WEB-INF/jsp/comm/pagingToolBar.jsp"一起使用
	 * <br/>使用"<jsp:include flush="true" page="/WEB-INF/jsp/comm/pagingToolBar.jsp" />"语句将分页工具条页面包含在你的页面中。
	 * @return 分页对象
	 */
	public PaginationSupport findPageByCriteria(DetachedCriteria detachedCriteria,HttpServletRequest request,String sessionStoreName) {
		if(request.getSession().getAttribute(sessionStoreName) != null) {
			request.getSession().setAttribute(sessionStoreName, request.getSession().getAttribute(sessionStoreName).toString());
		}
		else
		{
			request.getSession().setAttribute(sessionStoreName, "10");
		}
		int pageSize = Integer.valueOf(request.getSession().getAttribute(sessionStoreName).toString()).intValue();
		int startIndex = 0;
		if(request.getParameter("startIndex") != null) {
			startIndex = Integer.valueOf(request.getParameter("startIndex")).intValue();
		}
		return findPageByCriteria(detachedCriteria, pageSize, startIndex);
	}
}
